﻿using czj_shop.Models.Database;
using czj_shop.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace czj_shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CarController : ControllerBase
    {
        private readonly czj_shopContext _db;
        private readonly CarService _carService;
        /// <summary>
        /// 用户Id
        /// </summary>
        public int UId => Convert.ToInt32(Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
        /// <summary>
        /// 购物车控制器
        /// </summary>
        /// <param name="db"></param>
        public CarController(czj_shopContext db, CarService carService)
        {
            _db = db;
            _carService = carService;
        }

        //加入购物车接口（需授权） 输入：商品Id 输出：加入消息
        /// <summary>
        /// 加入购物车接口
        /// </summary>
        /// <param name="goodId"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public string AddCar(int goodId)
        {
            //实现加入购物车
            //用户点击加入购物车按钮 把商品加入购物车

            //1、用户购物车原来就有这个商品
            //更新购物车商品数量+1

            //登录用户IduserIdz
            var car = _carService.GetCar(UId, goodId);
            var result = false;
            if (car != null)
            {
                result = _carService.UpdateCarCount(car, 1);
            }
            //2、原来没有商品
            //创建购物车记录
            else
            {
                result = _carService.AddCar(goodId, UId);
            }
            if (result)
                return "加入成功";
            return "加入失败";
        }

        //减少购物车接口（需授权） 输入：商品Id 输出：减少消息
        /// <summary>
        /// 减少购物车接口
        /// </summary>
        /// <param name="goodId"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public string UpdateCar(int goodId)
        {
            //查询用户购物车有无该商品
            var car = _carService.GetCar(UId, goodId);
            var result = false;
            //如果有可以减少
            if (car != null)
            {
                //1、购物车商品数量==1 再减少 删除这个购物车商品
                if (car.quantity == 1)
                {
                    result = _carService.DeleteCar(car);
                }
                //2、正常减少更新数量
                else
                {
                    result = _carService.UpdateCarCount(car, -1);
                }
                if (result)
                    return "减少成功";
                return "减少失败";
            }
            //如果没有减少不了 什么情况会没有呢？
            else
            {
                return "购物车商品不存在";
            }
        }
    }
}
